package Login;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;

import javax.swing.JOptionPane;



public class user{
	

	/**
	 * 根据输入的str在文件中找，输入的是用户名+空格+密码的形式，
	 * @param str
	 * @param fileName
	 * @return
	 */
	public static boolean check(String str,String fileName) {
		boolean out=false;//输出
		try {
			FileInputStream f = new FileInputStream(fileName);			
			InputStreamReader isr = new InputStreamReader(f,"UTF-8");
			BufferedReader br = new BufferedReader(isr);
			
			String line = "";//按行读取
			while((line = br.readLine()) != null) {//文件未读取完
				if (line.equals(str) ) {
					out = true;
					break;
				} 
			}

			br.close();	//关闭
	        isr.close();
	        f.close();
		} catch (Exception e) {	
			e.printStackTrace();
		}
		return out;
	}
	/**
	 * 判断用户的姓名是否是新的，不重复的
	 * @param name
	 * @param fileName
	 * @return
	 */
	public static boolean isNew(String name,String fileName) {
		boolean out=false;//输出
		try {
			FileInputStream f = new FileInputStream(fileName);			
			InputStreamReader isr = new InputStreamReader(f,"UTF-8");
			BufferedReader br = new BufferedReader(isr);
			
			String line = "";//按行读取
			while((line = br.readLine()) != null) {//文件未读取完
				String[] temp = line.split(" ");
				if (temp[0].equals(name) ) {
					out = true;
					break;
				}
			}

			br.close();	//关闭
	        isr.close();
	        f.close();
		} catch (Exception e) {	
			e.printStackTrace();
		}
		return out;
	}
	
	
	/**
	 * 写入用户信息str，成功则返回true
	 * @param str
	 * @param fileName
	 * @return
	 */
	public static boolean writeUser(String str,String fileName) {
		boolean out = false;
		try {
			FileWriter fw = new FileWriter(fileName,true);
			
			fw.write("\n"+str);//写入新的信息
			fw.close();
			
			out = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return out;
	}
	
	
	/**
	 * 注册
	 * @param name
	 * @param password
	 * @param fileName
	 * @return
	 */
	public static boolean register(String name,String password,String fileName) {
		boolean out = false;//输出
		if(isNew(name, fileName)) {//先判断是否重名
			return out;
		}else {	
			 writeUser(name+" "+password, fileName);//写入
			out = true;
		}
		return out;
	}
}

	
	
